<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../dist/swiper-bundle.min.css">
    <title>闪购首页</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            padding: 10px 20px;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }

        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #ff6666;
        }

        .nav {
            display: flex;
            align-items: center;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            margin: 0 10px;
        }

        .nav .welcome {
            color: #999;
        }

        .nav .logout {
            color: #ff6666;
            cursor: pointer;
        }

        main {
            width: 90%;
            margin: 20px auto;
        }

        .banner {
            background-color: #fff;
            padding: 10px;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .banner .swiper {
            width: 100%;
            height: 300px;
        }

        .banner .swiper img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .seckill {
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .seckill .seckill-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .seckill .seckill-header h2 {
            font-size: 20px;
            color: #ff6666;
        }

        .seckill .countdown span {
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #333;
            color: #fff;
            text-align: center;
            line-height: 30px;
            margin-right: 5px;
            border-radius: 4px;
        }

        .seckill .seckill-list {
            display: flex;
            flex-wrap: wrap;
            margin: 10px;
        }

        .seckill .seckill-item {
            width: 150px;
            text-align: center;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 10px;
        }

        .seckill .seckill-item img {
            width: 100%;
            height: auto;
            margin-bottom: 10px;
            object-fit: cover;
        }

        .seckill .seckill-item span {
            color: #ff6666;
            font-size: 14px;
            display: block;
            margin-bottom: 10px;
        }

        .seckill .seckill-item .seckill-btn {
            text-decoration: none;
            color: black;
            background-color: #fff;
            padding: 3px 6px;
            border-radius: 4px;
            display: inline-block;
            cursor: pointer;
        }

        .seckill .seckill-item .seckill-btn:hover {
            background-color: #e05555;
        }

        .hot-products {
            background-color: #fff;
            padding: 20px;
            margin-bottom: 20px;
        }

        .hot-products h2 {
            font-size: 20px;
            margin-bottom: 20px;
            color: #333;
        }

        .hot-products .product-list {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .hot-products .product-item {
            text-align: center;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            height: 300px;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .hot-products .product-item img {
            width: 100%;
            height: 60%;
            margin-bottom: 10px;
        }

        .hot-products .product-item p {
            margin-bottom: 5px;
            font-weight: bold;
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .hot-products .product-item span {
            color: #ff6666;
            font-size: 14px;
            display: block;
            margin-bottom: 10px;
        }

        .hot-products .product-item a {
            text-decoration: none;
            color: #fff;
            background-color: #ff6666;
            padding: 6px 12px;
            border-radius: 4px;
            align-self: center;
        }

        .hot-products .product-item a:hover {
            background-color: #e05555;
        }

        footer {
            text-align: center;
            padding: 10px;
            background-color: #333;
            margin-top: 20px;
            color: #999;
        }
    </style>
</head>

<body>
    <header>
        <div class="logo">闪购</div>
        <div class="nav">
            <a href="index.html" class="active">首页</a>
            <a href="cart.html">购物车 <span id="cartCount">0</span></a>
            <span class="welcome">欢迎, <span id="username">游客</span></span>
            <span class="logout" onclick="logout()">退出登录</span>
        </div>
    </header>

    <main>
        <section class="banner">
            <div class="swiper mySwiper">
                <div class="swiper-wrapper">
                    <div class="swiper-slide"><img src="../images/swiper1.jfif" /></div>
                    <div class="swiper-slide"><img src="../images/swiper2.jfif" /></div>
                    <div class="swiper-slide"><img src="../images/swiper3.jfif" /></div>
                </div>
                <div class="swiper-pagination"></div>
                <div class="swiper-button-prev"></div>
                <div class="swiper-button-next"></div>
            </div>
        </section>

        <section class="seckill">
            <div class="seckill-header">
                <h2>限时秒杀</h2>
                <div class="countdown">
                    <span id="hour">24</span>时
                    <span id="minute">00</span>分
                    <span id="second">00</span>秒
                </div>
            </div>
            <div class="seckill-list">
                <div class="seckill-item">
                    <img src="../images/phone.webp" />
                    <p>智能手机</p>
                    <span>¥1999</span>
                    <a href="#" class="seckill-btn"
                        onclick="addToCart(1, '智能手机', 1999, '../images/phone.webp'); return false;">立即抢购</a>
                </div>
                <div class="seckill-item">
                    <img src="../images/notebook.jfif" />
                    <p>笔记本电脑</p>
                    <span>¥4999</span>
                    <a href="#" class="seckill-btn"
                        onclick="addToCart(2, '笔记本电脑', 4999, '../images/notebook.jfif'); return false;">立即抢购</a>
                </div>
                <div class="seckill-item">
                    <img src="../images/earphone.jfif" />
                    <p>无线耳机</p>
                    <span>¥699</span>
                    <a href="#" class="seckill-btn"
                        onclick="addToCart(3, '无线耳机', 699, '../images/earphone.jfif'); return false;">立即抢购</a>
                </div>
            </div>
        </section>

        <section class="hot-products">
            <h2>热门商品</h2>
            <div class="product-list" id="productList">
            </div>
        </section>
    </main>

    <footer>
        <p>©2025 闪购</p>
    </footer>

    <script src="../dist/swiper-bundle.min.js"></script>
    <script>
        function initProductData() {
            if (!localStorage.getItem('product')) {
                const productData = [
                    {
                        id: 1,
                        name: '智能手机',
                        price: 2999,
                        image: '../images/phone.webp',
                        description: '最新款智能手机，搭载高性能处理器，6.5英寸全面屏，4800万像素四摄，5000mAh大电池。',
                    },
                    {
                        id: 2,
                        name: '笔记本电脑',
                        price: 5999,
                        image: '../images/notebook.jfif',
                        description: '轻薄笔记本电脑，第11代酷睿i5处理器，16GB内存，512GB固态硬盘，14英寸高清屏幕。',
                    },
                    {
                        id: 3,
                        name: '无线耳机',
                        price: 899,
                        image: '../images/earphone.jfif',
                        description: '真无线蓝牙耳机，主动降噪，通话降噪，长续航，IPX4防水，触控操作。',
                    },
                    {
                        id: 4,
                        name: '智能手表',
                        price: 1299,
                        image: '../images/smartwatch.jfif',
                        description: '多功能智能手表，心率监测，血氧检测，睡眠监测，50米防水，长达14天续航。',
                    },
                    {
                        id: 5,
                        name: '平板电脑',
                        price: 3699,
                        image: '../images/pad.jfif',
                        description: '10.9英寸全面屏平板，A14仿生芯片，4GB内存，64GB存储，支持Apple Pencil。',
                    },
                    {
                        id: 6,
                        name: '蓝牙音箱',
                        price: 499,
                        image: '../images/bluetoothSpeaker.jfif',
                        description: '便携式蓝牙音箱，360°环绕立体声，IPX7级防水，24小时续航，支持TWS双音箱串联。',
                    }
                ]
                localStorage.setItem('product', JSON.stringify(productData));
            }
        }

        // 初始化轮播
        const swiper = new Swiper('.mySwiper', {
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            autoplay: {
                delay: 3000,
                disableOnInteraction: false,
            },
            loop: true,
        });

        // 处理用户名显示
        const usernameSpan = document.getElementById('username');
        const storedUsername = localStorage.getItem('username');
        if (storedUsername) {
            usernameSpan.textContent = storedUsername;
        } else {
            usernameSpan.textContent = '游客';
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('username');
            window.location.href = 'login.html';
        }

        // 秒杀倒计时
        function countdown() {
            const hourEle = document.getElementById('hour');
            const minuteEle = document.getElementById('minute');
            const secondEle = document.getElementById('second');
            let totalSeconds = 23 * 3600 + 59 * 60 + 50;
            const timer = setInterval(() => {
                if (totalSeconds <= 0) {
                    clearInterval(timer);
                    return;
                }
                const hours = Math.floor(totalSeconds / 3600);
                const minutes = Math.floor((totalSeconds % 3600) / 60);
                const seconds = totalSeconds % 60;
                hourEle.textContent = hours.toString().padStart(2, '0');
                minuteEle.textContent = minutes.toString().padStart(2, '0');
                secondEle.textContent = seconds.toString().padStart(2, '0');
                totalSeconds--;
            }, 1000);
        }

        // 渲染商品列表
        function renderProducts() {
            const productList = document.getElementById('productList');
            const products = JSON.parse(localStorage.getItem('product'));

            if (!products || products.length === 0) {
                productList.innerHTML = '<p style="text-align:center; width:100%;">暂无商品数据</p>';
                return;
            }

            products.forEach(product => {
                const productItem = document.createElement('div');
                productItem.className = 'product-item';
                productItem.innerHTML = `
          <img src="${product.image}" alt="${product.name}">
          <p>${product.name}</p>
          <span>¥${product.price}</span>
          <a href="detail.html?id=${product.id}">查看详情</a>
        `;
                productList.appendChild(productItem);
            });
        }

        // 添加商品到购物车
        function addToCart(id, name, price, image) {
            const username = localStorage.getItem('username');
            if (!username) {
                if (confirm('请先登录才能添加商品到购物车，是否前往登录？')) {
                    window.location.href = 'login.html';
                }
                return;
            }

            // 获取所有用户的购物车数据
            const allCarts = JSON.parse(localStorage.getItem('allCarts') || '{}');
            // 获取当前用户的购物车（默认空数组）
            const userCart = allCarts[username] || [];

            // 检查商品是否已在购物车中
            const existingItemIndex = userCart.findIndex(item => item.id === id);
            if (existingItemIndex > -1) {
                // 已存在则增加数量
                userCart[existingItemIndex].quantity = (userCart[existingItemIndex].quantity || 1) + 1;
                alert(`已将${name}添加到购物车，当前数量：${userCart[existingItemIndex].quantity}`);
            } else {
                // 不存在则添加新商品
                userCart.push({ id, name, price, image, quantity: 1 });
                alert(`${name}已成功添加到购物车！`);
            }

            // 保存更新后的购物车数据
            allCarts[username] = userCart;
            localStorage.setItem('allCarts', JSON.stringify(allCarts));

            // 更新购物车数量显示
            updateCartCount();
        }

        // 更新购物车数量显示
        function updateCartCount() {
            const username = localStorage.getItem('username');
            if (!username) {
                document.getElementById('cartCount').textContent = '0';
                return;
            }

            // 登录用户显示其专属购物车数量
            const allCarts = JSON.parse(localStorage.getItem('allCarts') || '{}');
            const userCart = allCarts[username] || [];
            const totalCount = userCart.reduce((sum, item) => sum + (item.quantity || 1), 0);

            document.getElementById('cartCount').textContent = totalCount;
        }

        // 页面加载时初始化
        window.onload = function () {
            initProductData();
            countdown();
            renderProducts();
            updateCartCount();
        };
    </script>
</body>

</html>